package com.meilai.project.service.business.offer.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.business.offer.OfferFlowDTO;
import com.meilai.project.dto.workflow.FlowBusinessDataSuperEntity;
import com.meilai.project.dto.workflow.WorkFlowCheckDTO;
import com.meilai.project.entity.business.offer.Offer;
import com.meilai.project.entity.business.offer.OfferFlow;
import com.meilai.project.entity.business.offer.OfferTmp;
import com.meilai.project.entity.system.Dictionary;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.business.offer.OfferFlowMapper;
import com.meilai.project.service.business.offer.OfferFlowService;
import com.meilai.project.service.business.offer.OfferService;
import com.meilai.project.service.business.offer.OfferTmpService;
import com.meilai.project.service.system.DictionaryService;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.util.WorkFlowUtil;
import com.meilai.project.vo.business.offer.OfferVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 报价审核表 服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-01-11
 */
@Service
public class OfferFlowImpl extends ServiceImpl<OfferFlowMapper, OfferFlow> implements OfferFlowService {

    @Autowired
    private OfferTmpService offerTmpService;

    @Autowired
    private OfferService offerService;

    @Autowired
    private DictionaryService dictionaryService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(OfferFlowDTO dto, Boolean tmpFlag, Long wf_data_id) {
        Long userId = ThreadLocalUserUtil.get().getId();
        Long mainDeptId = ThreadLocalUserUtil.get().getMain_department_id();
        String hyName = "";
        if (dto.getOfferTmps().size() > 0) {
            Dictionary dict = dictionaryService.getById(dto.getOfferTmps().get(0).getIndustry_id());
            hyName = dict.getName();
        }
        FlowBusinessDataSuperEntity startSuperDataEntity = WorkFlowUtil.getStartSuperDataEntity(userId, mainDeptId, 6, hyName + "行业报价" + "审核");
        OfferFlow flow = new OfferFlow();
        BeanUtils.copyProperties(startSuperDataEntity, flow);
        flow.setCreated(dto.getCreated());
        flow.setId(dto.getId());
        Boolean flag = this.saveOrUpdate(flow);
        Boolean b = flow.getId().equals(dto.getId());
        if (!tmpFlag) {
            dto.setId(flow.getId());
        }
        dto.getOfferTmps().forEach(item -> item.setOffer_flow_id(flow.getId()));//ROUND_HALF_UP
        offerTmpService.remove(Wrappers.<OfferTmp>lambdaQuery().eq(OfferTmp::getOffer_flow_id, dto.getId()));
        return flag &&
                offerTmpService.saveBatch(dto.getOfferTmps()) && (tmpFlag && !b) ? (wf_data_id != null ? new WorkFlowUtil<OfferFlow, OfferFlowMapper>(flow.getId(), userId, OfferFlow.class).SaveDraft(wf_data_id) == 1 : new WorkFlowUtil<OfferFlow, OfferFlowMapper>(flow.getId(), userId, OfferFlow.class).SaveDraft() == 1) : true;//(0L, "", new OfferFlow()) == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAndStartFlow(OfferFlowDTO dto, Long wfData_id) {
        // 当前人
        Long userId = ThreadLocalUserUtil.get().getId();

        OfferFlow flow = new OfferFlow();
        Boolean flag = this.save(dto, false, null);
        BeanUtils.copyProperties(dto, flow);
        return flag && new WorkFlowUtil<OfferFlow, OfferFlowMapper>(dto.getId(), userId, OfferFlow.class).Begin(wfData_id != null ? wfData_id : -1L, "", flow) == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean check(Long id, Boolean is_return, String opinion) {
        // 当前人
        Long userId = ThreadLocalUserUtil.get().getId();

        OfferFlow flow = this.getById(id);
        Long curCheckIndex = WorkFlowUtil.getCurCheckIndex(flow.getFlow_json(), flow.getFlow_current_node_id());
        int result = -1;
        if (!is_return) {
            result = new WorkFlowUtil<OfferFlow, OfferFlowMapper>(flow.getId(), userId, OfferFlow.class).ToNext(new WorkFlowCheckDTO(flow.getFlow_current_node_id(), curCheckIndex, opinion, ""));
        } else {
            result = new WorkFlowUtil<OfferFlow, OfferFlowMapper>(flow.getId(), userId, OfferFlow.class).ReturnBack(new WorkFlowCheckDTO(flow.getFlow_current_node_id(), curCheckIndex, opinion, ""));
        }
        if (result == 2) {
            if (!is_return) {
                List<OfferVO> list = offerTmpService.getMediaVO(id);
                long industry_id = -1L;
                if (list.size() > 0) {
                    industry_id = list.get(0).getIndustry_id();
                }
                offerService.remove(Wrappers.<Offer>lambdaQuery().eq(Offer::getIndustry_id, industry_id).isNull(Offer::getDeleted_at));
                return offerService.saveBatch(
                        list.stream().map(item -> {
                            Offer offer = new Offer();
                            BeanUtils.copyProperties(item, offer);
                            offer.setId(null);
                            return offer;
                        }).collect(Collectors.toList())
                );
            } else {
                return true;
            }
        } else if (result == 1) {
            return true;
        } else {
            throw new CommonException("审核失败");
        }
    }


    @Override
    public Page<OfferFlow> page(Integer page, Integer page_size, String name, Boolean is_check_page) {
        Page<OfferFlow> dataPage = new Page<>();
        Long id = ThreadLocalUserUtil.get().getId();
        List<OfferFlow> list = null;
        if (is_check_page) {
            list = baseMapper.page(dataPage, name, null);
            for (OfferFlow flow : list) {
                flow.setCheck(WorkFlowUtil.canCheckData(id, flow));
            }
        } else {
            list = baseMapper.page(dataPage, null, id);
        }
        dataPage.setRecords(list);
        return dataPage;
    }

    @Override
    public Integer getCount() {
        Long userId = ThreadLocalUserUtil.get().getId();
        return this.count(Wrappers.<OfferFlow>lambdaQuery().eq(OfferFlow::getFlow_applyer_id, userId).isNull(OfferFlow::getDeleted_at).eq(OfferFlow::getFlow_status, 3));
    }


    @Override
    public OfferFlow getInfoById(Long id) {
        Long userId = ThreadLocalUserUtil.get().getId();
        OfferFlow flow = this.getById(id);
        flow.setCheck(WorkFlowUtil.canCheckData(userId, flow));
        return flow;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean remove(Long flow_id, Long wf_data_id) {
        Long userId = ThreadLocalUserUtil.get().getId();
        return new WorkFlowUtil<OfferFlow, OfferFlowMapper>(flow_id, userId, OfferFlow.class).Delete(wf_data_id) == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean actualDelete(Long flow_id, Long wf_data_id) {
        Long userId = ThreadLocalUserUtil.get().getId();
        return new WorkFlowUtil<OfferFlow, OfferFlowMapper>(flow_id, userId, OfferFlow.class).ActualDelete(wf_data_id) == 1;
    }
}
